package com.nhc.activity_fragment;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.TypedValue;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;

import com.astrob.nhcmap.R;
import com.astrob.view.BaseViewHolder;
import com.nhc.model.TripDataFileHandle;
import com.nhc.model.TripDatainfo;

import java.util.ArrayList;
import java.util.List;

import zuo.biao.library.base.BaseActivity;
import zuo.biao.library.base.BaseAdapter;
import zuo.biao.library.manager.TimeRefresher;
import zuo.biao.library.model.Entry;
import zuo.biao.library.ui.AlertDialog;
import zuo.biao.library.ui.PageScroller;
import zuo.biao.library.ui.TopMenuWindow;

/**
 * 使用方法：复制>粘贴>改名>改代码
 */

/**
 * activity示例
 *
 * @warn 复制到其它工程内使用时务必修改import R文件路径为所在应用包名
 * @use toActivity(DemoActivity.createIntent(...));
 */
public class ChangeDataTypeActivity extends BaseActivity implements AlertDialog.OnDialogButtonClickListener, TimeRefresher.OnTimeRefreshListener {
    private final String TAG = "ChangeDataTypeActivity";

    //启动方法<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
    static final String INTENT_DATA_INDEX = "INTENT_DATA_INDEX";

    /**
     * 启动这个Activity的Intent
     *
     * @param context
     * @return
     */

    public static Intent createIntent(Context context, int index) {
        return new Intent(context, ChangeDataTypeActivity.class)
                .putExtra(INTENT_DATA_INDEX, index);
    }

    //启动方法>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    int _index = -1;

    @Override
    public Activity getActivity() {
        return this;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //TODO demo_activity改为你所需要的layout文件；传this是为了底部左右滑动手势
        setContentView(R.layout.changedatatype_activity);

        intent = getIntent();
        _index = intent.getIntExtra(INTENT_DATA_INDEX, _index);

        //功能归类分区方法，必须调用<<<<<<<<<<
        initView();
        initData();
        initEvent();
        //功能归类分区方法，必须调用>>>>>>>>>>
    }


    //UI显示区(操作UI，但不存在数据获取或处理代码，也不存在事件监听代码)<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
    //示例代码<<<<<<<<
    private ListView lvDatatypeline;

    //示例代码>>>>>>>>
    @Override
    public void initView() {//必须在onCreate方法内调用
        autoSetTitle();//自动设置标题为上个Activity传入的INTENT_TITLE

        //示例代码<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
        lvDatatypeline = (ListView) findViewById(R.id.lvDatatypeline);
        //示例代码>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    }

    //示例代码<<<<<<<<
    private DemoAdapter adapter;
    //示例代码>>>>>>>>

    /**
     * 示例方法 ：显示列表内容
     *
     * @param list
     */
    private void setList(List<Entry<Integer, String>> list) {
        if (adapter == null) {
            adapter = new DemoAdapter(context);
            lvDatatypeline.setAdapter(adapter);

            adapter.setSelected(_index);
            if (_index > 0) {
//                if (android.os.Build.VERSION.SDK_INT >= 8) {
//                    lvDatatypeline.smoothScrollToPosition(_index);
//                } else {
//                    lvDatatypeline.setSelection(_index);
//                }
                lvDatatypeline.setSelection(_index);
            }
        }

        adapter.refresh(list);

    }

    //UI显示区(操作UI，但不存在数据获取或处理代码，也不存在事件监听代码)>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>


    //Data数据区(存在数据获取或处理代码，但不存在事件监听代码)<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
    //示例代码<<<<<<<<
    private List<Entry<Integer, String>> datatypelist;

    boolean _isFirst = true;

    boolean _isWorking = false;
    //示例代码>>>>>>>>>
    @Override
    public void initData() {//必须在onCreate方法内调用
        //示例代码<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
        if (_isFirst) {
//            showProgressDialog(R.string.loading);
        }
        if (_isWorking) {
            return;
        }
        _isWorking = true;

//        runThread(TAG + "initData", new Runnable() {
//            @Override
//            public void run() {
//                try {
//                    datatypelist = getList();
//                }catch(Exception e) {
//                    e.printStackTrace();
//                }
//                runUiThread(new Runnable() {
//                    @Override
//                    public void run() {
//                        if (_isFirst) {
//                            dismissProgressDialog();
//                            _isFirst = false;
//                        }
//                        setList(datatypelist);
//                        _isWorking = false;
//                    }
//                });
//            }
//        });

        datatypelist = getList();
        setList(datatypelist);
        _isWorking = false;
        //示例代码>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    }


    protected List<Entry<Integer, String>> getList() {
        if (datatypelist == null) {
            datatypelist = new ArrayList<Entry<Integer, String>>();
        }
        datatypelist.clear();
        for (int i = 0; i < TripDatainfo.DATATYPE_NAMES.length; i++) {
            String CC[] = TripDataFileHandle.getInstance().mTripDatainfo.getInfo(i);
            String content = CC[0] + CC[1];
            datatypelist.add(new Entry<Integer, String>(i, content));
        }
        return datatypelist;
    }

    //Data数据区(存在数据获取或处理代码，但不存在事件监听代码)>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>


    //Event事件区(只要存在事件监听代码就是)<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
    @Override
    public void initEvent() {//必须在onCreate方法内调用
        //示例代码<<<<<<<<<<<<<<<<<<<
        lvDatatypeline.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                selectType(position);
            }
        });

        //分页滚动示例代码<<<<<<<<<<<<<<<<<<<
        new PageScroller(lvDatatypeline).init();
        //分页滚动示例代码>>>>>>>>>>>>>>>>>>>

        //示例代码>>>>>>>>>>>>>>>>>>>
    }


    public static final String RESULT_VALUE = "RESULT_VALUE";

    private void selectType(int position) {
//        intent = new Intent();
//        intent.putExtra(RESULT_VALUE, _index);
//        setResult(RESULT_OK, intent);
        _index = position;
        finish();
    }

    //系统自带监听方法<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
    //@user 新增方法

    @Override
    public void finish() {
        setResult(_index);
        super.finish();
    }


    @Override
    public void onForwardClick(View v) {
        //top栏右边按钮响应
        toActivity(TopMenuWindow.createIntent(context, getResources().getStringArray(R.array.top_menu_trip)), REQUEST_TO_TOP_MENU, false);
    }

    @Override
    public void onDialogButtonClick(int requestCode, boolean isPositive) {
        if (isPositive == false) {
            return;
        }

        if (requestCode == 0) {
            int[] DATATYPE_INDEXS = {24, 21, 29, 30, 18, 20, 31, 32};
            TripDataFileHandle.getInstance().mTripDatainfo.DATATYPE_INDEXS = DATATYPE_INDEXS;
            TripDataFileHandle.getInstance().mTripDatainfo.reset();
            TripDataFileHandle.getInstance().save();
            _index = -1;
            finish();
        } else if (requestCode == 1) {
            TripDataFileHandle.getInstance().mTripDatainfo.reset();
            TripDataFileHandle.getInstance().save();
            adapter.notifyDataSetChanged();
        }

    }

    private final int REQUEST_TO_TOP_MENU = 30;

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            return;
        }
        switch (requestCode) {
            case REQUEST_TO_TOP_MENU:
                if (data != null) {
                    switch (data.getIntExtra(TopMenuWindow.RESULT_POSITION, -1)) {
                        case 0:
                            new AlertDialog(context, getString(R.string.alert_title), getString(R.string.revertfactory), true, 0, this).show();
                            break;
                        case 1:
                            new AlertDialog(context, getString(R.string.alert_title), getString(R.string.alert_resetrinfo), true, 1, this).show();
                            break;
                        default:
                            break;
                    }
                }
                break;
        }
    }

    @Override
    public void onTimerStart() {

    }

    @Override
    public void onTimerRefresh() {
        initData();
    }

    @Override
    public void onTimerStop() {

    }


    //系统自带监听方法>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    //Event事件区(只要存在事件监听代码就是)>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>


    //Adapter
    public class DemoAdapter extends BaseAdapter<Entry<Integer, String>> {
        public DemoAdapter(Activity context) {
            super(context);
        }

        private int mSelected = -1;

        public void setSelected(int selected) {
            mSelected = selected;
            notifyDataSetChanged();
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                convertView = LayoutInflater.from(context).inflate(
                        R.layout.datatype_view, parent, false);
            }

            TextView tv_name = BaseViewHolder.get(convertView, R.id.tv_name);
            TextView tv_name_selected = BaseViewHolder.get(convertView, R.id.tv_name_selected);
            TextView tv_content = BaseViewHolder.get(convertView, R.id.tv_content);

            final Entry<Integer, String> kvb = getItem(position);
            int index = kvb.getKey();
            if (index < 0 || index >= TripDatainfo.DATATYPE_NAMES.length) {
                index = 0;
            }
            tv_name.setText(TripDatainfo.DATATYPE_NAMES[index]);
            tv_name_selected.setText(TripDatainfo.DATATYPE_NAMES[index]);

            if (mSelected == position) {
                tv_name_selected.setVisibility(View.VISIBLE);
                tv_name.setVisibility(View.GONE);
            } else {
                tv_name_selected.setVisibility(View.GONE);
                tv_name.setVisibility(View.VISIBLE);
            }

            try {
                String content = kvb.getValue();
                tv_content.setText(content);

                if (content.length() > 15) {
                    tv_content.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 13);
                } else if (content.length() > 10) {
                    tv_content.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 15);
                } else {
                    tv_content.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 20);
                }
            }catch(Exception e) {
                e.printStackTrace();
            }

            return super.getView(position, convertView, parent);
        }

        private final long serialVersionUID = 3L;

        @Override
        public long getItemId(int position) {
//            return getItem(position).getId();
            return serialVersionUID + position;
        }

    }

    @Override
    protected void onResume() {
        super.onResume();
        TimeRefresher.getInstance().addTimeRefreshListener(TAG, 1000, this);
        if (lvDatatypeline != null) {
            lvDatatypeline.setSelection(_index);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        TimeRefresher.getInstance().removeTimeRefreshListener(TAG);
    }

}